<?php

namespace App\Http\Services;

use App\Http\Repositories\Daos\Course\CourseDao;
use App\Http\Requests\UserContext;
use App\Http\Traits\Errors;
use App\Http\Traits\GlobalConstant;
use App\Models\Campus;
use App\Models\Category;
use App\Models\CourseDutyTeacher;
use App\Models\CourseSection;
use App\Models\Teacher;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class TeacherService extends BaseService
{
    use Errors;

    protected $courseDao;

    public function __construct(CourseDao $courseDao)
    {
        $this->courseDao = $courseDao;
    }

    public function lists(UserContext $userContext)
    {
        $teacherId = $userContext->getTeacherId();
        if (empty($teacherId)) $this->showError('当前用户没有审核通过的老师身份，请补充完善老师信息');
        $lat       = request('lat') ?? 0;
        $lng       = request('lng') ?? 0;
        $state     = request('state') ?? 1;
        $condition = [
            'valid'      => 1,
            'teacher_id' => $teacherId
        ];
        $page      = request('page') ?? 1;
        $size      = request('size') ?? 10;
        $offset    = ($page * $size) - $size;
        $now       = time();
        $list      = $this->courseDao->getModel()->where($condition)
            ->whereIn('id', function ($query) use ($now, $state) {
                $query->select('course_id')->groupBy('course_id')->from('course_section');
                if ($state == 1) {
                    $query->havingRaw('MAX(end_time) > ?', [$now]);
                }
                if ($state == 2) {
                    $query->havingRaw('MAX(end_time) < ?', [$now]);
                }
            })
            ->with(["campusInfo" => function ($query) use ($lng, $lat) {
                if (!empty($lat) && !empty($lng)) {
                    $query->select(DB::raw("id, name,contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"));
                } else {
                    $query->select(['id', 'name', 'contact', 'logo', 'longitude', 'latitude', 'address']);
                }
            }])
            ->withCount(["courseSectionInfo", "courseSectionCompleteInfo"])
            ->limit($size)->offset($offset)->orderBy('created_at', 'desc')->get();
        if (!empty($list)) {//有距离显示时转换距离
            foreach ($list as &$item) {
                $item['distance'] = $item->campusInfo->distance >= 1000 ? round($item->campusInfo->distance / 1000, 1) . "km" : ceil($item->campusInfo->distance) . "m";
            }
            unset($item);
        }
        return $list;
    }

    public function detail()
    {
        $courseId = request('c_id') ?? 0;
        $lat      = request('lat') ?? 0;
        $lng      = request('lng') ?? 0;
        $info     = $this->courseDao->getModel()->where('id', $courseId)->with(["courseSectionInfo" => function ($query) {
            $query->orderBy('begin_time');
        }])->withCount("courseSectionInfo")->withCount("courseSectionCompleteInfo")
            ->first();
        if (!$info) {
            return new \stdClass();
        }
        $campus_info             = Campus::where('id', $info['campus_id'])->select(DB::raw("id, name,contact,logo,longitude,latitude,address,(6371 * acos(cos(radians(latitude)) * cos(radians($lat)) * cos(radians(longitude) - radians($lng)) + sin(radians(latitude)) * sin(radians($lat))))*1000 AS distance"))->first();
        $campus_info['distance'] = $campus_info['distance'] >= 1000 ? round($campus_info['distance'] / 1000, 1) . "km" : ceil($campus_info['distance']) . "m";
        $info->campus_info       = $campus_info;
        if ($info->courseSectionInfo) {
            $flag = true;
            foreach ($info->courseSectionInfo as $key => $item) {
                $temp                  = GlobalConstant::formatAllTimeOrHour(strtotime($item->class_time), $item->begin_time);
                $item->show_hui        = time() > $temp ? 1 : 0;
                $item->show_yuan_index = 2000;
                if ($flag && time() < $temp) {
                    $item->show_yuan_index = $key;
                    $info->sksj            = $item->sk_time . ' ' . $item->begin_time . '-' . $item->end_time;
                    $flag                  = false;
                }
            }
            if ($flag) {//如果已经结课则上课时间显示最后一节课的时间
                $array      = $info->courseSectionInfo->toArray();
                $end        = end($array);
                $info->sksj = $end['sk_time'] . ' ' . $end['begin_time'] . '-' . $end['end_time'];
            }
        }
        return $info;
    }

    public function statics(UserContext $userContext)
    {
        $now       = time();
        $teacherId = $userContext->getTeacherId();
        $pending   = $this->courseDao->getModel()->where('teacher_id', $teacherId)->where('valid', 1)->whereIn('id', function ($query) use ($now) {
            $query->select('course_id')->groupBy('course_id')->havingRaw('MAX(end_time) > ?', [$now])->from('course_section');
        })->count();
        $complete  = $this->courseDao->getModel()->where('teacher_id', $teacherId)->where('valid', 1)->whereIn('id', function ($query) use ($now) {
            $query->select('course_id')->groupBy('course_id')->havingRaw('MAX(end_time) < ?', [$now])->from('course_section');
        })->count();
        return [['status' => 1, 'total' => $pending], ['status' => 2, 'total' => $complete]];
    }

    public function gateStatics(UserContext $userContext)
    {
        $teacherId = $userContext->getTeacherId();
        $courseId  = request('course_id') ?? 0;
        if (empty($courseId)) {
            $had    = CourseDutyTeacher::where('teacher_id', $teacherId)->count();
            $total  = CourseSection::whereIn('course_id', function ($query) use ($teacherId) {
                $query->where('teacher_id', $teacherId)->select('id')->from('course');
            })->count();
            $future = CourseSection::whereIn('course_id', function ($query) use ($teacherId) {
                $query->where('teacher_id', $teacherId)->select('id')->from('course');
            })->where('begin_time', '>=', time())->where('status', 1)->count();//再查所有未到上课的章节
        } else {
            $had    = CourseDutyTeacher::where('teacher_id', $teacherId)->where('course_id', $courseId)->count();
            $total  = CourseSection::whereIn('course_id', function ($query) use ($teacherId, $courseId) {
                $query->where('teacher_id', $teacherId)->where('course_id', $courseId)->select('id')->from('course');
            })->where('course_id', $courseId)->count();
            $future = CourseSection::whereIn('course_id', function ($query) use ($teacherId, $courseId) {
                $query->where('teacher_id', $teacherId)->where('id', $courseId)->select('id')->from('course');
            })->where('begin_time', '>=', time())->where('status', 1)->count();//再查所有未到上课的章节
        }

        return compact("total", "had", "future");
    }

    public function gateStatics2(UserContext $userContext)
    {
        $teacherId = $userContext->getTeacherId();
        $courseId  = request('course_id') ?? 0;
        if (empty($courseId)) {
            $res    = DB::select('SELECT

                          COUNT(*) AS had
                        FROM
                          (SELECT
                            course_section_id,
                            COUNT(DISTINCT sign_type) AS sign_types
                          FROM
                            course_duty_teacher
                          WHERE sign_type IN (1, 2) and teacher_id =?
                          GROUP BY course_section_id, teacher_id
                          HAVING sign_types = 2) AS subquery', [$teacherId]);
            $total  = CourseSection::whereIn('course_id', function ($query) use ($teacherId) {
                $query->where('teacher_id', $teacherId)->select('id')->from('course');
            })->count();
            $future = CourseSection::whereIn('course_id', function ($query) use ($teacherId) {
                $query->where('teacher_id', $teacherId)->select('id')->from('course');
            })->where('begin_time', '>=', time())->where('status', 1)->count();//再查所有未到上课的章节
        } else {
            $res    = DB::select('SELECT

                          COUNT(*) AS had
                        FROM
                          (SELECT
                            course_section_id,
                            COUNT(DISTINCT sign_type) AS sign_types
                          FROM
                            course_duty_teacher
                          WHERE sign_type IN (1, 2) and teacher_id =? and course_id=?
                          GROUP BY course_section_id, teacher_id
                          HAVING sign_types = 2) AS subquery', [$teacherId, $courseId]);
            $total  = CourseSection::whereIn('course_id', function ($query) use ($teacherId, $courseId) {
                $query->where('teacher_id', $teacherId)->where('course_id', $courseId)->select('id')->from('course');
            })->where('course_id', $courseId)->count();
            $future = CourseSection::whereIn('course_id', function ($query) use ($teacherId, $courseId) {
                $query->where('teacher_id', $teacherId)->where('id', $courseId)->select('id')->from('course');
            })->where('begin_time', '>=', time())->where('status', 1)->count();//再查所有未到上课的章节
        }

        $had = $res[0]->had;
        return compact("total", "had", "future");
    }

    public function teacherDetail(UserContext $userContext)
    {
        $userId = $userContext->getId();
        $info   = Teacher::where('user_id', $userId)->first();
        if (empty($info)) {
            return ['info' => new \stdClass(), 'approve_status' => 0];
        }
        Log::info('进入教师信息编辑，user_id' . $userId . '存在教师信息' . $info['id']);
        $approve_status         = $info ? $info['approve_status'] : 0;
        $info['category_ids']   = explode(',', $info['category_ids']);
        $info['category_names'] = '';
        if (!empty($info['category_ids'])) {
            $category = Category::whereIn('id', $info['category_ids'])->get()->toArray();
            Log::info('分类信息', ['dasda' => json_encode($info)]);
            if (!empty($category)) {
                foreach ($category as $item) {
                    $data[] = $item['name'];
                }
                $info['category_names'] = $data;
            }
        }
        return compact("info", "approve_status");
    }

    public function save(UserContext $userContext)
    {
        $userId    = $userContext->getId();
        $data      = request()->post();
        $validator = Validator::make($data, [
            'avatar'  => 'required',
            'name'    => 'required',
            'mobile'  => 'required',
            'age'     => 'required',
            'edu_max' => 'required',
            'sex'     => 'required',
            'num'     => 'required',
            'person'  => 'required',
//            'intro'   => 'required',
        ], [
                'avatar.required'  => '请上传头像',
                'name.required'    => '真实姓名不能为空',
                'mobile.required'  => '联系电话不能为空',
                'age.required'     => '请选择年龄区间',
                'edu_max.required' => '请选择学历',
                'sex.required'     => '请选择性别',
                'num.required'     => '授课次数不能为空',
                'person.required'  => '授课人数不能为空',
//                'intro.required'   => '请填写教学经历或技能简介',
            ]
        );
        if ($validator->fails()) $this->showError($validator->errors()->first());
        $data['user_id'] = $userId;
        $data['intro']   = $data['intro'] ?? '';
        $info            = Teacher::where('user_id', $userId)->first();
        if (!$info) {
            Teacher::create($data);
            return true;
        }
        $info->fill($data);
        $info->save();
        return true;
    }

}
